package com.atguiguNIO.channel;

import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.DatagramChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.util.Iterator;
import java.util.Set;

public class DatagramChannel01 {


    public static void main(String[] args) {
        try {
            DatagramChannel channel = DatagramChannel.open();
            channel.configureBlocking(false);
            //如果在两台物理计算机中进行实验，则要把localhost改成服务端的IP地址
            channel.bind(new InetSocketAddress("localhost", 8080));
            Selector selector = Selector.open();
            channel.register(selector, SelectionKey.OP_READ);

            while (true) {
                selector.select();
                Set<SelectionKey> selectionKeys = selector.selectedKeys();
                Iterator<SelectionKey> it = selectionKeys.iterator();
                while (it.hasNext()) {
                    SelectionKey key = it.next();
                    if (key.isReadable()) {
                        for (int i = 0; i < 10; i++) {
                            channel = (DatagramChannel) key.channel();
                            ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
                            SocketAddress socketAddress = channel.receive(byteBuffer);
                            System.out.println(new String(byteBuffer.array(), 0, byteBuffer.position()));
                            byteBuffer.flip();
                            System.out.println(socketAddress.toString());
                            Thread.sleep(3000);
                        }
                    }
                    it.remove();
                }
                channel.close();
                System.out.println("server 关闭............");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }



}
